package com.elangzhi.ssm.modules.user.app;

import com.alibaba.fastjson.JSONObject;
import com.elangzhi.ssm.controller.json.Tip;
import com.elangzhi.ssm.model.Account;
import com.elangzhi.ssm.model.Advice;
import com.elangzhi.ssm.model.Talk;
import com.elangzhi.ssm.model.User;
import com.elangzhi.ssm.modules.advice.services.AdviceService;
import com.elangzhi.ssm.modules.goodsComment.services.GoodsCommentService;
import com.elangzhi.ssm.modules.image.services.ImageService;
import com.elangzhi.ssm.modules.talk.services.TalkService;
import com.elangzhi.ssm.modules.user.services.OpenIMService;
import com.elangzhi.ssm.modules.user.services.ThinksService;
import com.elangzhi.ssm.modules.user.services.UserService;
import com.elangzhi.ssm.services.AccountService;
import com.elangzhi.ssm.tools.Const;
import com.elangzhi.ssm.tools.SMSUtil;
import com.elangzhi.ssm.tools.UUIDFactory;
import com.taobao.api.ApiException;
import com.taobao.api.domain.Userinfos;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
* 用户 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/app/user")
public class AppUserController {


    @RequestMapping(value = "/invitation", method = RequestMethod.POST)
    @ResponseBody
    public Tip invitation( @RequestParam  String phone){
        SMSUtil.sendInvitation(phone);
        return new Tip();
    }

    /**
     * 获取用户个人资料信息
     * @param id 用户id
     * @return 个人信息、评价、说说
     */
    @ResponseBody
    @RequestMapping(value="/findInfoById")
    public User findInfoById(Long id){
        User user = userService.selectById(id);

        user.setComments(goodsCommentService.listByGoodsId(id,1,1).getList());
        Talk talk = new Talk();
        talk.setMyId(id);
        List<Talk> talks = talkService.listByRegion(talk,1,1).getList();
        for(Talk t : talks) {
            t.setBannerList(imageService.listByTypeInfo(4, t.getId()));
        }
        user.setTalks(talks);
        return user;
    }

    /**
     * 获取钱包信息
     * @param thinksId
     */
    @ResponseBody
    @RequestMapping(value="/qianbao")
    public JSONObject qianbao(String thinksId){
        JSONObject jsonObject = thinksService.currency(thinksId);
        return jsonObject;
    }


    /**
     * 转账
     * @param thinksId 我方id
     * @param toUserThinksId 被转账方
     * @param num 数量
     * @return 成功状态
     */
    @ResponseBody
    @RequestMapping(value="/zhuanzhang")
    public JSONObject zhuanzhang(String thinksId,String toUserThinksId,String num){
        JSONObject jsonObject = thinksService.zhuanzhang(thinksId,toUserThinksId,num);
        return jsonObject;
    }

    /**
     * 发送验证码 用于更改密码
     * @param phone 手机号信息
     * @return 发送状态
     * 1，没有此账号
     * 2，发送失败
     */
    @ResponseBody
    @RequestMapping(value="/sendCodePwd")
    public Tip sendCodePwd(String phone){

        Advice advice = new Advice();
        advice.setId(UUIDFactory.getLongId());
        advice.setType(2);
        advice.setReaded(1);
        advice.setUserId(Long.valueOf(phone));
        advice.setContent(UUIDFactory.getCode6());
        advice.setSetTime(new Date());
        advice.setTitle("发送验证码");
        try {
            adviceService.insert(advice);
            SMSUtil.sendCode(phone,advice.getContent());
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(2);
        }
    }

    /**
     * 更改密码
     * @param thinksId 用户账号
     * @param newPwd 新密码
     * @param code 短信验证码
     * @return 更改状态
     * 1，此账户不存在
     * 2，验证码错误
     * 3，密码更改失败
     */
    @ResponseBody
    @RequestMapping(value="/changePwd")
    public Tip changePwd(String thinksId,String newPwd,String code) {
        User user = userService.selectByThinksId(thinksId);
        if(user == null){return new Tip(2);}
        // 获取上次的验证码
        List<Advice> list = adviceService.listByTypeUser(2, Long.parseLong(user.getPhone()));
        if (list.size() == 0) {
            return new Tip(2);
        }
        Advice advice = list.get(0);
        // 验证验证码
        if(code.equals(advice.getContent())){

            try {
                JSONObject jsonObject = thinksService.passwordEdit(user.getThinksId(),newPwd);
                if(!jsonObject.getBoolean("status")){
                    return new Tip(1,jsonObject);
                }
                return new Tip();
            } catch (Exception e) {
                e.printStackTrace();
                return new Tip(3);
            }
        }else{
            return new Tip(2);
        }
    }

    /**
     * 修改资料
     * @param id 用户id
     * @param nick 昵称
     * @param wechat 微信号
     * @param qq QQ号
     * @param sex 性别
     * @param intro 个性签名
     * @return 状态
     */
    @ResponseBody
    @RequestMapping(value="/updateInfo")
    public Tip updateInfo(Long id,
                          @RequestParam(required = false) String nick,
                          @RequestParam(required = false) String wechat,
                          @RequestParam(required = false) String qq,
                          @RequestParam(required = false) String sex,
                          @RequestParam(required = false) String intro){
        User user = userService.selectById(id);
        try {
            JSONObject jsonObject = thinksService.userEdit(user.getThinksId(),nick,wechat,qq);
            if(!jsonObject.getBoolean("status")){
                return new Tip(2);
            }

            user.setNickName(nick);
            user.setWechat(wechat);
            user.setQq(qq);
            user.setSex(sex);
            user.setIntro(intro);
            userService.updateById(user);

            // 更改IM账号信息
            updateOpenIm(user);

            return new Tip(user);
        } catch (Exception e) {
            System.out.println("更改用户信息失败");
            e.printStackTrace();
            return new Tip(1);
        }
    }

    /**
     * 修改头像
     * @param request 请求头
     * @param file 头像文件
     * @param id 用户id
     * @return 成功状态
     */
    @ResponseBody
    @RequestMapping(value="/changeHead")
    public Tip changeHead(
            HttpServletRequest request,
            @RequestParam(value = "file") MultipartFile file,
            @RequestParam Long id
            ){
        if (file != null) {
            try {
                String fileName = file.getOriginalFilename();
                String saveName = UUIDFactory.getLongId() + fileName.substring(fileName.lastIndexOf("."));
                //保存地址
                String saveUrl = "/images/headImage/" + "user_" + saveName;
                String filePath =  request.getServletContext().getRealPath(saveUrl);
                file.transferTo(new File(filePath));

                User user = userService.selectById(id);
                user.setHead(saveUrl);
                userService.updateById(user);

                //更改阿里百川头像
                openIMService.changeImg(user.getThinksId(),saveUrl);

                return new Tip(saveUrl);
            } catch (IOException e) {
                e.printStackTrace();
                return new Tip(2);
            } catch (Exception e) {
                e.printStackTrace();
                return new Tip(3);
            }
        } else {
            return new Tip(1);
        }
    }



    /**
     * 发送验证码
     * @param phone 手机号
     * @return 成功状态
     * 1，发送失败
     */
    @ResponseBody
    @RequestMapping(value="/sendCode")
    public Tip sendCode(String phone){

        Advice advice = new Advice();
        advice.setId(UUIDFactory.getLongId());
        advice.setType(1);
        advice.setReaded(1);
        advice.setUserId(Long.valueOf(phone));
        advice.setContent(UUIDFactory.getCode6());
        advice.setSetTime(new Date());
        advice.setTitle("发送验证码");
        try {
            adviceService.insert(advice);
            SMSUtil.sendCode(phone,advice.getContent());
            return new Tip();
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(2);
        }
    }

    /**
     * 注册账号
     * @param thinksId 账号
     * @param password 密码
     * @param phone 手机号
     * @param nick 昵称
     * @param code 验证码
     * @return 状态
     */
    @ResponseBody
    @RequestMapping(value="/register")
    public Tip register(String thinksId,String password,String phone,String nick,String code){

        List<Advice> list = adviceService.listByTypeUser(1,Long.valueOf(phone));
        if(list.size() == 0){
            return new Tip(2);
        }
        Advice advice = list.get(0);
        if(code.equals(advice.getContent())){
            try {

                JSONObject jsonObject = thinksService.register(thinksId,password,phone,nick,"888888");
                if(!jsonObject.getBoolean("status")){
                    return new Tip(1);
                }

                User user = userService.selectByThinksId(thinksId);
                if(user == null){
                    user = new User();
                    user.setId(UUIDFactory.getLongId());
                    user.setNickName(nick);
                    user.setHead("/images/account/defaultHead.jpg");
                    user.setPhone(phone);
                    user.setThinksId(thinksId);
                    userService.insert(user);
                    addOpenIm(user);
                }

                // 注册im账号

                return new Tip(user);
            } catch (Exception e) {
                e.printStackTrace();
                return new Tip(3);
            }
        }else{
            return new Tip(2);
        }

    }


    /**
     * 登陆
     * @param thinksId 用户名
     * @param password 密码
     * @return 状态
     * 1,登陆失败
     * 2，账号密码错误
     */
    @ResponseBody
    @RequestMapping(value="/login")
    public Tip login(String thinksId,String password)  {

        JSONObject jsonObject = thinksService.login(thinksId,password);
        try {
            if(jsonObject.getBoolean("status")){
                JSONObject dataJson = JSONObject.parseObject(jsonObject.getString("data"));
                User user = initUser(dataJson,thinksId);
                return new Tip(user);
            }else{
                return new Tip(2,jsonObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1,jsonObject);
        }

    }

    /**
     * 验证并初始化用户
     * @param thinksId 用户名
     */
    private User initUser(JSONObject dataJson,String thinksId) throws Exception {
        User user = userService.selectByThinksId(thinksId);
        if(user == null){
            user = new User();
            user.setId(UUIDFactory.getLongId());
            user.setThinksId(dataJson.getString("userid"));
            user.setPhone(dataJson.getString("phone"));
            user.setNickName(dataJson.getString("nick"));
            user.setWechat(dataJson.getString("wechat"));
            user.setQq(dataJson.getString("qq"));
            user.setName(dataJson.getString("name"));
            user.setHead("/images/account/defaultHead.jpg");
            userService.insert(user);
            addOpenIm(user);
        }else{
            user.setPhone(dataJson.getString("phone"));
            user.setNickName(dataJson.getString("nick"));
            user.setWechat(dataJson.getString("wechat"));
            user.setQq(dataJson.getString("qq"));
            user.setName(dataJson.getString("name"));
            userService.updateById(user);
            addOpenIm(user);
            updateOpenIm(user);
        }
        return user;
    }

    /**
     * 初始化openIm信息
     * @param user 用户信息
     */
    private void addOpenIm(User user) throws ApiException {
        Userinfos userinfos = new Userinfos();
        userinfos.setNick(user.getNickName());
        userinfos.setUserid(user.getThinksId());
        userinfos.setPassword("123456");
        userinfos.setQq(user.getQq());
        userinfos.setName(user.getName());
        userinfos.setMobile(user.getPhone());
        userinfos.setWechat(user.getWechat());
        openIMService.addUser(userinfos);
    }


    /**
     * 初始化openIm信息
     * @param user 用户信息
     */
    private void updateOpenIm(User user) throws ApiException {
        Userinfos userinfos = new Userinfos();
        userinfos.setNick(user.getNickName());
        userinfos.setUserid(user.getThinksId());
        userinfos.setPassword("123456");
        userinfos.setQq(user.getQq());
        userinfos.setName(user.getName());
        userinfos.setMobile(user.getPhone());
        userinfos.setWechat(user.getWechat());
        openIMService.changeUser(userinfos);
    }

    /**
     * 注销登陆回话
     * @param session session
     * @return 成功状态
     */
    @ResponseBody
    @RequestMapping(value="/logout")
    public Tip logout(HttpSession session){
        try {
            session.removeAttribute(Const.ACCOUNT);
            session.removeAttribute(Const.USER);
            return new Tip();
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1);
        }
    }


    //---------------------------- property -------------------------------

    @Resource
    private GoodsCommentService goodsCommentService;

    @Resource
    private ImageService imageService;

    @Resource
    private TalkService talkService;

    @Resource
    private UserService userService;

    @Resource
    private AccountService accountService;

    @Resource
    private AdviceService adviceService;

    @Resource
    private ThinksService thinksService;
    
    @Resource
    private OpenIMService openIMService;
}
